
import React, { Component } from 'react'
import PropTypes from 'prop-types'
import { bindActionCreators } from 'redux'
import { connect } from 'react-redux'
import {Switch } from 'antd-mobile';
import * as Actions from '../../actions'
import Header from '../../components/Header'
import utils from '../../utils'
import OrderProductItem from '../../components/OrderProductItem'
import MeScrollContainer from '../../components/MeScroll'



class ConfirmationOrder extends Component{
  static contextTypes={
    router:PropTypes.object.isRequired,
  }
  constructor(props) {
    super(props);
    this.state={
      checked:false,
      score:-1
    }
  }
  componentDidMount(){
    let {actions} =this.props 
    actions.getCartListbyStore()
    actions.getAddressList({},{isCache:true})
    actions.getScoreInfo({},{callback:(res)=>{
      if(res.code ==200 && res.data){
        this.setState({ ...res.data,score:res.data.total_score - res.data.frozen_score})
      }
    }})

   
  }
  onTextChange(type,e){
    this.setState({
      [type]:e.target.value
    })
  }
  submit(){
    let {actions,cartList,address } = this.props

    let cart_ids=[]
    cartList.map(item =>{
      if(item.checked)
        cart_ids.push(item.cart_id)

    })

    let data={
      cart_id:cart_ids.join(','),
      recv_addr_id:address.addr_id,
      use_score:this.state.checked?1:0,
      note:this.state.note||''

    }
    actions.buyByCart(data,{callback:(res)=>{
      if(res.code ==200){
         //下单成功后，把商品从购物车中删除
        actions.delCarts({cart_id:cart_ids.join(',')})
        utils.msg({text:res.message,code:1})
        this.context.router.history.push('/order/pay')

      }
     
    }})
  }
  changeAddress(){
    this.context.router.history.push('/address/list/order')
  }
  addAddress(){
    this.context.router.history.push('/address/edit/0')
  }
  render(){
    let { cartList,address} =this.props 
    let {checked ,score} =this.state
    let selectedList=cartList.filter(item => item.checked)

    let init={money:0,score:0}
    var sum = selectedList.reduce((initJson={money:0,score:0},next)=>{
        initJson.money = (next.goods_num * next.goods_price) + initJson.money;
        initJson.score = (next.goods_use_score * next.goods_price) + initJson.score;
        return initJson
    }, init);

    return(
      <div className='order-container '>
        <Header title={'Order confirmation'} leftBtn={true} leftBtnTouch={()=>{
          this.context.router.history.goBack()
        }}/>
        <MeScrollContainer >
          {/*地址 begin*/}
          {
            address.addr_id>0?
            <div className='address-context' onClick={this.changeAddress.bind(this)}>
              <i className='iconfont icon-dizhi'></i>
              <div className='aleft'>
                <p className="p1">addressee：<span className='txt'>{address.recv_name}  {address.recv_mobile}</span></p>
                <p className="p2" style={{'paddingTop':"8px"}}>Address of the consignee：
                  <span className='txt'>{address.recv_country}{address.recv_province||''}{address.recv_city||''}{address.recv_area||''}{address.recv_address||''}</span>
                </p>
              </div>
              <div className='aright'><i className='iconfont icon-jiantou'></i></div>
            </div>
          :
            <div className='address-context' style={{'textAlign':"center"}} onClick={this.addAddress.bind(this)}>
              <div className='aleft'>
               <i className='iconfont icon-add'></i> add address
              </div>
              <div className='aright'><i className='iconfont icon-jiantou'></i></div>
            </div>
          }
          
          {/*地址 end*/}
          
          {
            sum.score >0 && score < sum.score? 
            <div className='score-tip'>Only {score} of your points are not enough to exchange the current goods</div>
            :null
          }

          {/*商品 begin*/}
          {
            selectedList.map((item,i) =>{
              return(
                <div key={i}>
                  <OrderProductItem item={item}  fromPage ={'order'} />
                </div>
                
                )
            })
          }
          {/*商品 end*/}

          <div className='buyer-context margin-top-10'>
            <div className='input-item'>
              <span className='s1'>Buyer's notes:</span>
              <input value={this.state.note||''}  onChange={this.onTextChange.bind(this,'note')} type="text" className='s2' />
            </div>
          </div>
          {
            sum.score >0 && score>= sum.score?
            <div className='buyer-context margin-top-10'>
              <div className='input-item between'>

                <span className='s1'>{score} points can be used to offset ${score}</span>
                <Switch checked={checked} className='s3' onClick={(checked) => { this.setState({ checked }) }} />
              </div>
            </div> 
            :
            null
              
          }
        
          </MeScrollContainer>

          <div className='bottom bordertop'>
            <div className='cart-left'>
              <span className='all-money'>Real payment: ${sum.money}</span>
            </div>
            <div className='cart-rigth'>
              <div className="del-btn" onClick={this.submit.bind(this)}> place order </div>
            </div>
          </div>
      </div>
    )
  }

  

}


function mapStateToProps(state){
  let addressList = state.addressList.toJS()
  let address =addressList.find(item => item.checked )
  if( !address)
    address =addressList.find(item => item.is_default ==1 ) || addressList[0] ||{}
  return {
    cartList:state.cartList.toJS(),
    address: address
  }
}
function mapDispatchToProps(dispatch) {
  return {
    actions: bindActionCreators(Actions, dispatch)
  }
}
export default  connect(
  mapStateToProps,
  mapDispatchToProps
)(ConfirmationOrder)
